package com.kotlin.android.app

import com.kotlin.android.api.base.BaseUIModel
import com.kotlin.android.api.base.call
import com.kotlin.android.api.base.callParallel
import com.kotlin.android.api.download.DownloadManager
import com.kotlin.android.api.download.listener.DownloadListener
import com.kotlin.android.app.data.user.LoginBean
import com.kotlin.android.app.ktx.FileEnv
import com.kotlin.android.app.repository.AppRepository
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.core.ext.versionCode

/**
 *

 */
class AppViewModel : BaseViewModel() {
    private val repo by lazy { AppRepository() }
    val uiModel by lazy { BaseUIModel<Map<Int, *>>() }

    // 获取用户信息
    val mRefreshTokenUIModel = BaseUIModel<LoginBean>()

    val downloadFileUIModel = BaseUIModel<String>()


    /**
     * 加载app启动相关服务配置信息
     * parameter count 有多少个api合并请求，只做提示，没有业务功能
     */
    fun loadAppService(count: Int) {
        callParallel(
            { repo.getAppVersion(appType = "ANDROID", versionCode = versionCode.toString()) },
            { repo.getShareQr() },
            uiModel = uiModel,
        )
    }

    /**
     * 刷新用户信息
     */
    fun getRefreshToken() {
        call(
            uiModel = mRefreshTokenUIModel,
        ) {
            repo.getRefreshToken()
        }
    }

    //http://www.pzshops.com/download/MainApp-debug.apk
    fun downLoadFile(url: String) {
        try {
            val lastIndexOf = url.lastIndexOf(".")
            if (lastIndexOf < 0) {
                downloadFileUIModel.emitUIState(showLoading = false, error = "链接不可为空")
                return
            }
            downloadFileUIModel.emitUIState(showLoading = true)
            DownloadManager.download(url,
                "${System.currentTimeMillis()}${url.substring(lastIndexOf)}",
                FileEnv.downDir,
                object : DownloadListener {
                    override fun onProgress(progress: Int) {
//                    "downloadFile下载进度：$progress".e()
                        downloadFileUIModel.emitUIState(progress = progress)
                    }

                    override fun onFailed(msg: String?) {
                        downloadFileUIModel.emitUIState(error = "下载失败请稍后重试")
                    }

                    override fun onComplete(filePath: String) {
                        downloadFileUIModel.emitUIState(success = filePath)
                    }
                })
        } catch (e: Exception) {
            downloadFileUIModel.emitUIState(error = "下载失败请稍后重试")
        }


    }


}